<template>
    <van-nav-bar
            title="订单确认"
            left-text="返回"
            left-arrow
            fixed
            @click-left="$router.go(-1)"
    ></van-nav-bar>

    <div class="main">
        <div class="contact-info" @click="showAddressList = true">
            <p class="name-and-phone">
                <span class="name">{{chosenAddress.name}}</span>
                <span class="phone">{{chosenAddress.tel}}</span>
            </p>
            <p>
                <span class="default" v-if="chosenAddress.isDefault === 1">[默认]</span>
                <span class="address">{{chosenAddress.address}}</span>
            </p>
        </div>

        <van-cell :title="cartItemCount"/>

        <van-cell v-for="item in cartInfo" :key="item.id" class="product">
            <img :src="item.productInfo.image">
            <div class="info">
                <p class="title show-in-one-lines">{{ item.productInfo.store_name }}</p>
                <p class="price">￥{{ item.truePrice }}</p>
            </div>
            <span class="count">x{{ item.cart_num }}</span>
        </van-cell>
    </div>

    <van-submit-bar :price="totalPrice * 100" label="订单总计：" button-text="立即付款" @submit="handlePay">
    </van-submit-bar>

    <!-- 地址列表 - 弹出层 -->
    <van-popup v-model:show="showAddressList" position="bottom">
        <van-address-list
                v-model="chosenAddressId"
                :list="addressList"
                default-tag-text="默认"
                @select="handleSelectAddress"
                @add="onAdd"
                @edit="onEdit"
        ></van-address-list>
    </van-popup>

    <Pay
            :showPayPopup="showPayPopup"
            @changeShow="value => showPayPopup = value"
            @pay="pay"
    ></Pay>
</template>

<script setup>
  import { defineProps, ref, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { Toast } from 'vant'
  import { getAddressList } from '@/api/address.js'
  import { confirmOrder, createOrder } from '@/api/order.js'
  import Pay from './components/pay.vue'

  const router = useRouter()

  const { cartIds } = defineProps({
    cartIds: String,
  })

  // 商品信息相关
  const orderConfirmData = ref({})
  const cartInfo = computed(() => orderConfirmData.value?.cartInfo)
  const cartItemCount = computed(() => `共${cartInfo.value?.length || 0}件`)
  const totalPrice = computed(() => orderConfirmData.value?.priceGroup?.totalPrice || 0)

  const initOrderInfo = async () => {
    const { data } = await confirmOrder(cartIds, 0)
    orderConfirmData.value = data
    console.log(data)
  }
  initOrderInfo()
  console.log('cartIds>>', cartIds)

  // 支付相关
  const handlePay = () => {
    showPayPopup.value = true
  }
  const showPayPopup = ref(false)
  const pay = async (payMethod) => {
    const { status } = await createOrder(orderConfirmData.value.orderKey, chosenAddress.value.id, payMethod)
    if (status === 200) {
      Toast.success('支付成功，正在跳转订单页...')
      router.push({
        name: 'order',
      })
    } else {
      Toast.fail('支付失败')
    }
  }

  // 选择地址相关
  const showAddressList = ref(false)
  const chosenAddressId = ref('0')
  const chosenAddress = ref({})
  const addressList = ref([]);

  (async () => {
    const { data } = await getAddressList({
      page: 0,
      limit: 5,
    })
    console.log(data)
    addressList.value = data.map(item => {
      return {
        id: String(item.id),
        name: item.real_name,
        tel: item.phone,
        address: `${item.province}${item.city}${item.district}${item.detail}`,
        isDefault: item.is_default,
      }
    })
    chosenAddressId.value = addressList.value[0].id
    chosenAddress.value = addressList.value[0]
  })()

  const handleSelectAddress = item => {
    chosenAddressId.value = item.id
    chosenAddress.value = item
    showAddressList.value = false
  }

  const onAdd = () => {
    router.push({
      name: 'address',
      params: {
        cartIds,
      }
    })
  }
  const onEdit = (item, index) => Toast('编辑地址:' + index)
</script>

<style lang="scss" scoped>
    .main {
        margin-top: 50px;
        margin-bottom: 50px;

        .contact-info {
            font-size: 16px;
            font-weight: 400;
            padding: 20px 25px;
            position: relative;

            .name-and-phone {
                margin-bottom: 5px;

                .name {
                    margin-right: 15px;
                }
            }

            .default {
                background: #D6251F;
                color: white;
                font-size: 12px;
                margin-right: 15px;
                padding: 2px 3px;
                border-radius: 3px;
            }

            &::after {
                content: '';
                position: absolute;
                left: 0;
                right: 0;
                bottom: 0;
                height: 2px;
                background: repeating-linear-gradient(90deg, #ff6c6c 0, #ff6c6c 20%, transparent 20%, transparent 25%, #0084ff 25%, #0084ff 45%, transparent 45%, transparent 50%);
                background-size: 80px;
            }
        }

        .product {
            :deep(.van-cell__value) {
                display: flex;
                align-items: center;
            }

            img {
                width: 70px;
                height: 70px;
            }

            .info {
                padding-left: 5px;

                .title {
                    padding: 0 15px 5px 0;
                }

                .price {
                    font-size: 14px;
                    color: #F2270C;
                }
            }

            .count {
                color: #aaa;
            }
        }
    }
</style>
